package com.example.framework;

import com.example.annotation.GQController;
import com.example.annotation.GQRequestMapping;
import com.example.annotation.GQRequestParam;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GQDispatchServlet/* extends HttpServlet*/ {

    //    private Map<Pattern, Handler> handlerMapping = new HashMap<>();
    private List<Handler> handlerMapping = new ArrayList<>();
    //    private Map<Handler, HandlerAdapter> adapterMapping = new HashMap<>();
    private List<HandlerAdapter> adapterMapping = new ArrayList<>();

    private List<GQViewResolver> viewResolvers = new ArrayList<>();

    //    @Override
    public void init() throws ServletException {
        GQApplicationContext context = new GQApplicationContext();
        // 解析 url 和 method 的 关联关系
        initHandlerMappings(context);
        // 适配器 匹配过程  主要是用来动态匹配我们的参数
        initHandlerAdapters(context);
        // 解析模板中的内容，拿到服务器传过来的数据，生成 HTML 代码
        initViewResolvers(context);

        initFlashMapManager(context);
    }

    /**
     * 解析 url 和 method 的 关联关系
     *
     * @param context
     */
    private void initHandlerMappings(GQApplicationContext context) {
        Map<String, Object> ioc = context.getAll();
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            if (!aClass.isAnnotationPresent(GQController.class)) {
                continue;
            }
            String url = "";
            if (aClass.isAnnotationPresent(GQRequestMapping.class)) {
                GQRequestMapping annotation = aClass.getAnnotation(GQRequestMapping.class);
                url = annotation.value();
            }
            // 扫描 controller 下面所有的方法
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(GQRequestMapping.class)) {
                    continue;
                }
                GQRequestMapping annotation = method.getAnnotation(GQRequestMapping.class);
                String regex = (url + annotation.value()).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
//                handlerMapping.put(pattern, new Handler(entry.getValue(), method));
                handlerMapping.add(new Handler(entry.getValue(), method, pattern));
                System.out.println("HandlerMapping-----:" + pattern + "-------:" + method.toString());
            }
        }
    }

    /**
     * 适配器 匹配过程
     *  主要是用来动态匹配我们的参数
     * @param context
     */
    public void initHandlerAdapters(GQApplicationContext context) {
        if (handlerMapping.isEmpty()) {
            return;
        }
        // 参数类型作为 key， 参数的索引号 作为 value
        Map<String, Integer> paramMapping = new HashMap<>();
        // 只需要取出具体的某个方法
        for (Handler handler : handlerMapping) {
            // 把这个方法的所有参数全部获取
            Class<?>[] parameterTypes = handler.method.getParameterTypes();
            // 有顺序，但是通过反射，没法拿到我们的参数名称
            // 自定义参数列表
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];
                if (parameterType == HttpServletRequest.class || parameterType == HttpServletResponse.class) {
                    paramMapping.put(parameterType.getName(), i);
                }
            }
            Annotation[][] parameterAnnotations = handler.method.getParameterAnnotations();
            for (int i = 0; i < parameterAnnotations.length; i++) {
                for (Annotation annotation : parameterAnnotations[i]) {
                    if (annotation instanceof GQRequestParam) {
                        String paramName = ((GQRequestParam) annotation).value();
                        if (!"".equals(paramName.trim())) {
                            paramMapping.put(paramName, i);
                        }
                    }
                }
            }
//            adapterMapping.put(handler, new HandlerAdapter(paramMapping));
            adapterMapping.add(new HandlerAdapter(paramMapping, handler));
        }
    }

    /**
     * 模板解析
     *
     * @param context
     */
    private void initViewResolvers(GQApplicationContext context) {
        // 加载模板的个数，存到缓存中
        // 归根到底就是一个普通的文件
        String templateRoot = context.getTemplatePath();
        String rootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
        List<File> fileList = new ArrayList<>();
        //  viewResolvers
        context.getAllFile(templateRoot, fileList);
        fileList.forEach(file -> new GQViewResolver(file.getName(), file));

    }

    /**
     * @param context
     */
    private void initFlashMapManager(GQApplicationContext context) {

    }

    ;

    //    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    //    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception , Msg : " + Arrays.toString(e.getStackTrace()));
        }
    }

    /**
     * @param req
     * @param resp
     */
    public void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            Handler handler = getHandler(req);
            if (handler == null) {
                resp.getWriter().write("404 Not Found handler... ");
                return;
            }
            // 在取出来一个适配器
            // 再由适配器调用具体的方法
            HandlerAdapter ha = getHandlerAdapter(handler);
            // 执行方法
            GQModelAndView mv = ha.handle(req, resp, handler);

            //写一个自己的模板
            //@{name}
            applyDefaultViewName(resp, mv);
//            mappedHandler.applyPostHandle(processedRequest, response, mv);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * @param resp
     * @param mv
     */
    private void applyDefaultViewName(HttpServletResponse resp, GQModelAndView mv) throws IOException {
        if (mv == null) {
            return;
        }
        GQViewResolver gqViewResolver = viewResolvers.stream().filter(element -> element.equals(mv.getView())).findAny().orElse(null);
        if (gqViewResolver != null) {
            String parse = gqViewResolver.parse(mv);
            if (parse != null) {
                resp.getWriter().write(parse);
            }
        }
    }

    /**
     * 获取 handler
     * 根据请求的路径获取对应的 handler == Map<String, Handler>
     *
     * @param req
     * @return
     */
    private Handler getHandler(HttpServletRequest req) {
        // 循环 handlerMapping
        if (handlerMapping.isEmpty()) {
            return null;
        }
        // 请求的全路径
        String requestURI = req.getRequestURI();
        // 请求的前缀
        String contextPath = req.getContextPath();
        // 去掉前缀
        String rul = requestURI.replace(contextPath, "").replaceAll("/+", "/");
        // 根据路径的正则匹配 handler
        for (Handler handler : handlerMapping) {
            Pattern pattern = handler.pattern;
            Matcher matcher = pattern.matcher(rul);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

    /**
     * 获取适配器
     *  根据 handler 获取对应的 HandlerAdapter
     *  handler： controller method
     *  HandlerAdapter  里面放置 参数 Map 和 method 的 执行 参数赋值 和 invoke
     * @param handler
     * @return
     */
    private HandlerAdapter getHandlerAdapter(Handler handler) {
        if (adapterMapping.isEmpty()) {
            return null;
        }
//        return adapterMapping.get(handler);
        for (HandlerAdapter adapter : adapterMapping) {
            if (adapter.getHandler() != handler) {
                continue;
            }
            return adapter;
        }
        return null;
    }

}
